package com.zyk.scaffold.user.mail.controller;

import com.zyk.scaffold.core.domain.Result;
import com.zyk.scaffold.common.utils.AssertUtil;
import com.zyk.scaffold.common.utils.MD5Util;
import com.zyk.scaffold.common.utils.StringUtils;
import com.zyk.scaffold.user.mail.AccountMailSenderManager;
import com.zyk.scaffold.user.mail.MailApiConstants;
import com.zyk.scaffold.user.mail.properties.LocalMailProperties;
import com.zyk.scaffold.user.mail.properties.MailApp;
import com.zyk.scaffold.user.mail.sender.ILocalMailSender;
import com.zyk.scaffold.user.mail.sender.SenderMessage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.security.NoSuchAlgorithmException;
import java.util.List;

@Api(tags = "邮件-API")
@Slf4j
@RestController
@RequestMapping("/mail")
public class MailController {

    @Autowired
    private LocalMailProperties localMailProperties;

    @Autowired
    private AccountMailSenderManager accountMailSenderManager;

    @ApiOperation("发送邮件")
    @PostMapping("/send")
    public Result<Boolean> listFunction(
            @RequestHeader(MailApiConstants.HEADER_MAIL_APP_KEY) String appKey,
            @RequestHeader(MailApiConstants.HEADER_MAIL_APP_SIGN) String sign,
            @RequestBody SenderMessage senderMessage) {
        if (validate(senderMessage, appKey, sign)) {
            ILocalMailSender mailSender = accountMailSenderManager.getMailSender(localMailProperties.getUseName());
            if (null == mailSender){
                log.error("邮件发送失败，账号配置不存在：{}", localMailProperties.getUseName());
                AssertUtil.error("邮件发送失败，账号配置不存在");
            }
            boolean send = mailSender.send(senderMessage);
            return Result.ok(send);
        }
        return Result.ok(Boolean.FALSE);
    }

    private boolean validate(SenderMessage senderMessage, String appKey, String sign) {
        if(senderMessage == null || StringUtils.isEmpty(appKey) || StringUtils.isEmpty(sign)) {
            return false;
        }
        List<MailApp> mailApps = localMailProperties.getMailApps();
        if(CollectionUtils.isEmpty(mailApps)){
            return false;
        }
        MailApp targetMailApp = null;
        for (MailApp mailApp : mailApps) {
            if (appKey.equals(mailApp.getAppKey())){
                targetMailApp = mailApp;
            }
        }
        if(targetMailApp == null){
            return false;
        }
        String s = null;
        try {
            s = MD5Util.computeMD5(appKey + "-" + senderMessage.toText() + "-" + targetMailApp.getAppSecret());
        } catch (NoSuchAlgorithmException e) {
            AssertUtil.error("签名校验异常！");
        }
        return sign.equals(s);
    }
}
